package com.ziyun.pop.web.config;

import com.alibaba.fastjson.JSONObject;
import com.ziyun.pop.common.token.RedisTokenManager;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * token 过滤器
 * @author zh
 * @date 2019/1/510:03
 */
public class TokenFilter extends AccessControlFilter {

    private RedisTokenManager redisTokenManager;

    public TokenFilter(RedisTokenManager redisTokenManager){
        this.redisTokenManager = redisTokenManager;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = ((HttpServletRequest) request).getHeader("token");
        if(StringUtil.isEmpty(token)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONObject.toJSON(R.apiError(1000,"token不能为空!")));
            out.flush();
            out.close();
            return false;
        }
        if(!redisTokenManager.isActive(token)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONObject.toJSON(R.apiError(1001,"登录过期,请重新登录!")));
            out.flush();
            out.close();
            return false;
        }else { //验证通过 刷新token 过期时间
            SysUserEntity sysUser = redisTokenManager.getUserInfoBToken(token);
            redisTokenManager.refreshToken(token);
            redisTokenManager.refreshToken(sysUser.getUserId() + sysUser.getUsername());
            HttpServletResponse resp = (HttpServletResponse)response;
            resp.setHeader("expireTime", String.valueOf(redisTokenManager.getExpire(token)));
            return true;
        }
    }
}
